﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SuperSocket.ProtoBase;
using System.Buffers;
using System.Linq;

using Xc.DataAccess.Protocoals.WaterMeters.Extensions;

namespace Xc.DataAccess.Protocoals.WaterMeters.Models
{
    public class MeterFramePipleFilter : PipelineFilterBase<MeterFrameRx>
    {
        public MeterFramePipleFilter()
        {

        }
        private readonly ILogger<MeterFramePipleFilter> logger;

        public override MeterFrameRx Filter(ref SequenceReader<byte> reader)
        {
            if (!reader.TryReadTo(out ReadOnlySequence<byte> equence, MeterFrameRx.StartConst, true))
            {
                logger?.LogDebug($"未找到包头:{MeterFrameRx.StartConst}");
                return null;
            }
            //表计类型
            if (!reader.TryRead(out var metertype))
            {
                logger?.LogDebug($"读取表具类型失败");
                return null;
            }
            if (!reader.TryRead(7,out ReadOnlySequence<byte> result))
            {
                logger?.LogDebug("待读取的数据包长度不足");
                return null;
            }
            if (!reader.TryRead(out var cmd))
            {
                logger?.LogDebug($"读取表具控制码失败");
                return null;
            }
            if (!reader.TryRead(out var length))
            {
                logger?.LogDebug($"读取表具数据域长度失败");
                return null;
            }
            if (length<2)
            {
                logger?.LogDebug($"表具数据域长度错误，长度小于2");
                return null;
            }
            //读取数据标识
            if (!reader.TryRead(length,out  ReadOnlySequence<byte> dataarea))
            {
                logger?.LogDebug($"读取表具数据域失败");
                return null;
            }
            if (!reader.TryRead(out var check))
            {
                logger?.LogDebug($"读取表具校验码失败");
                return null;
            }
            if (!reader.TryRead(out var foot))
            {
                logger?.LogDebug($"读取表具数据结尾符失败");
                return null;
            }
            if (foot== MeterFrameRx.StopConst)
            {
                MeterFrameRx meterFrame = new MeterFrameRx()
                {
                    DataArea= DataArea.FromSequence(dataarea),
                    Check = check,
                    Cmd = (FrameCommand)cmd,
                    Length = length,
                    MeterAddress = result.ToArray().Reverse().ToArray(),
                    MeterType = (MeterType)metertype,
                    Start = MeterFrameRx.StartConst,
                    Stop = MeterFrameRx.StopConst,
                    FullFrame= reader.Sequence.ToArray()
                };
                return meterFrame;
            }
            else
            {
                logger?.LogDebug($"读取表具数据结尾符错误,当前符号为：{foot}");
                return null;
            }
        }
    }

}
